/**
 *  @filename   :   epd7in5-demo.ino
 *  @brief      :   7.5inch e-paper display demo
 *  @author     :   Yehui from Waveshare
 *
 *  Copyright (C) Waveshare     August 25 2017
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documnetation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to  whom the Software is
 * furished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS OR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

#include <SPI.h>
#include "epd7in5b.h"
#include "imagedata.h"
#include <HTTPClient.h>
#include <Ticker.h> //调用Ticker.h库

//https://jeebox.xiaosiqi.me/admin/index.html#/iot/EPaperList  可在这个网站设置获取到的图片
String url = "http://jeebox.xiaosiqi.me:9001/iot/eImageGroup/getImg/1482724718737137666";
unsigned char *image;



//	WiFi的初始化和连接
void WiFi_Connect()
{
  WiFi.begin("PDCN", "1234567890");
  while (WiFi.status() != WL_CONNECTED)
  { //这里是阻塞程序，直到连接成功
    delay(300);
    Serial.print(".");
  }
  Serial.print("WIFI连接成功\n\r");
  Serial.print(WiFi.localIP());
  Serial.print("\n\r");
}

//	从网络获取图片
const unsigned char *getImageData()
{
  //创建 WiFiClient 对象。该对象用于处理getStream函数所获取的服务器响应体
  WiFiClient wifiClient;
  //创建 HTTPClient 对象
  HTTPClient http;

  http.setTimeout(60000);
  http.setConnectTimeout(60000);
  http.begin(url);
  int httpCode = http.GET();
  Serial.printf("响应状态码: %d\r\n", httpCode);
  // 收到正确的内容
  if (httpCode == HTTP_CODE_OK)
  {
    // 获取服务器响应体Stream并传递给wifiClient
    String data = http.getString();
    Serial.println("从服务器获取字节流\n\r");
    image = (unsigned char *)data.c_str();
    Serial.println("获取完成\n\r");
    return image;
  }
  else
  {
    Serial.printf("响应错误: %s\n", http.errorToString(httpCode).c_str());
    return IMAGE_DATA;
  }
  http.end();
}


Epd epd;

//显示图像
void printImg()
{
  Serial.println("刷新图像\n\r");

  //从网络获取图像
  const unsigned char *img = getImageData();
  //设置图像
  epd.DisplayOneQuarterFrameMy(img);
}

void setup()
{
  //打开串口
  Serial.begin(115200);
  delay(100);
  //连接WIFi
  WiFi_Connect();
  //初始化水墨屏
  if (epd.Init() != 0)
  {
    Serial.print("墨水屏初始化失败！\n\t");
    return;
  }
   Serial.print("墨水屏初始化完成\n\t");
  }

void loop()
{
  printImg();
  delay(1000000);
}
